package com.skyworth.web.admin.table.service.impl;

import com.google.common.collect.Lists;
import com.google.gson.JsonObject;
import com.skyworth.utils.StrUtil;
import com.skyworth.web.admin.table.form.TableForm;
import com.skyworth.web.admin.table.model.TableModel;
import com.skyworth.web.admin.table.repository.TableRepository;
import com.skyworth.web.admin.table.service.ITableService;
import com.skyworth.web.wechat.common.AppSecretInfo;
import com.skyworth.web.wechat.common.WxConstant;
import com.skyworth.web.wechat.engin.ServerEngin;
import com.skyworth.web.wechat.entity.AccessTokenModel;
import com.skyworth.web.wechat.repository.AccessTokenRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * Created by cody on 2016/8/11.
 */
@Service
public class TableServiceImpl implements ITableService {
    @Autowired
    private TableRepository repository;

    @Autowired
    private AccessTokenRepository accessTokenRepository;

    @Override
    public Iterable<TableModel> queryByManagerId(long id) {
        return repository.queryByManagerId(id);
    }

    @Override
    public Iterable<TableModel> queryByStoreId(Long id) {
        Iterable<TableModel> result = repository.queryByStoreId(id);
        return result;
    }

    @Override
    public TableModel saveOrUpdate(TableModel item) {
        TableModel tableModel = repository.save(item);
        tableModel = createTableQrc(tableModel);
        tableModel = repository.save(tableModel);
        return tableModel;
    }

    @Override
    public TableModel addTable(TableForm tableForm) {
        TableModel tableModel = new TableModel();
        tableModel.name = tableForm.getName();
        tableModel.seating = tableForm.getSeating();
        tableModel.managerId = tableForm.getManagerId();
        tableModel.storeId = tableForm.getStoreId();
        tableModel.state = tableForm.getState();
        tableModel = repository.save(tableModel);

        tableModel = createTableQrc(tableModel);
        tableModel = repository.save(tableModel);
        return tableModel;
    }

    @Override
    public TableModel updateTable(TableForm storeForm) {
        TableModel tableModel = this.findTable(storeForm.getId());
        tableModel.name = storeForm.getName();
        tableModel.seating = storeForm.getSeating();
        tableModel.managerId = storeForm.getManagerId();
        tableModel.state = storeForm.getState();

        if(tableModel.qrcUrl==null || "".equals(tableModel.qrcUrl) || tableModel.qrcImg==null || "".equals(tableModel.qrcImg)) {
            tableModel = createTableQrc(tableModel);
        }
        tableModel = repository.save(tableModel);
        return tableModel;
    }

    @Override
    public boolean existTable(String name) {
        return repository.existsByName(name);
    }

    @Override
    public void removeTable(long id) {
        repository.delete(id);
    }

    @Override
    public TableModel findTable(long id) {
        return repository.findOne(id);
    }

    @Override
    public List<TableModel> tableList(JsonObject params) {
        return Lists.newArrayList(repository.findAll());
    }

    @Override
    public Page<TableModel> tablePage(JsonObject params, Pageable pageable) {
        if(params != null){
            long store_id = params.get("store_id").getAsLong();
            return repository.allValidTable(store_id, pageable);
        }
        return repository.findAll(pageable);
    }

    @Override
    public void updateTableState(long tableId) {
        repository.updateTableState(tableId);
    }

    @Override
    public boolean existTable(String name, long id) {
        return repository.existsTable(name,id);
    }

    @Override
    public boolean existTableByStore(String name, long store_id) {
        return repository.existsTableByStore(name,store_id);
    }

    private TableModel createTableQrc(TableModel tableModel){
        try {
            if (tableModel != null && tableModel.id > 0) {
                AccessTokenModel accessTokenModel = accessTokenRepository.findOne(AppSecretInfo.appId);
                Map<Object, Object> qrcMap = ServerEngin.getInstance().getQrcInfo(accessTokenModel.getAccessToken(), String.valueOf(tableModel.id));
                if (qrcMap != null && qrcMap.get("url") != null && qrcMap.get("ticket") != null) {
                    String qrcUrl = StrUtil.objectToString(qrcMap.get("url"));
                    String ticket = StrUtil.objectToString(qrcMap.get("ticket"));
                    try {
                        ticket = URLEncoder.encode(ticket, "utf-8");
                    } catch (UnsupportedEncodingException e) {
                    }
                    String qrcImg = WxConstant.QRC_IMG_URL + ticket;
                    tableModel.qrcUrl = qrcUrl;
                    tableModel.qrcImg = qrcImg;
                }
            }
        }catch(Exception e){
        }
        return tableModel;
    }
}
